package com.glory.gloryquickui.view

import android.content.Context
import android.view.View
import android.widget.CompoundButton
import android.widget.TextView
import android.widget.ToggleButton
import com.glory.gloryquickui.R
import com.glory.gloryquickui.entity.FieldBean
import com.glory.gloryquickui.viewmodel.QuickUIViewModel

/**
 *开关组件
 */
class ToggleButtonController(context: Context?, val viewModel: QuickUIViewModel) :
    ViewController<FieldBean?>(context) {
    private var tvTextName: TextView? = null
    private var tvInActiveText: TextView? = null
    private var tvActiveText: TextView? = null
    private var tbIsYes: ToggleButton? = null
    override fun resLayoutId(): Int {
        return R.layout.layout_toggle_button
    }

    override fun onBindView(data: FieldBean?) {
        tvTextName!!.text = data?.config?.label
        tbIsYes!!.isChecked = data!!.config.defaultValue as Boolean
        //设置禁用
        tbIsYes?.isEnabled = !data.disabled
        //设置前面文字
        if (data.inactiveText != "") {
            tvInActiveText?.visibility = View.VISIBLE
            tvInActiveText?.text = data.inactiveText
        }
        //设置后面文字
        if (data.activeText != "") {
            tvActiveText?.visibility = View.VISIBLE
            tvActiveText?.text = data.activeText
        }

        tbIsYes?.setOnCheckedChangeListener { _: CompoundButton, b: Boolean ->
            data.config.defaultValue = b
            val map = viewModel.pageData.value!!.toMutableMap()
            map[data!!.vModel] = if (b) "true" else "false"
            viewModel.pageData.value = map
        }
    }

    override fun onCreatedView(view: View?) {
        tvTextName = view?.findViewById(R.id.tvTextName)
        tvInActiveText = view?.findViewById(R.id.tvInActiveText)
        tvActiveText = view?.findViewById(R.id.tvActiveText)
        tbIsYes = view?.findViewById(R.id.tbIsYes)
    }

    override fun masterPart(): View? {
        return tbIsYes
    }
}